package com.spboot.controller;

import com.spboot.util.Result;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.web.bind.annotation.CrossOrigin;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpServletResponse;
import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.util.UUID;

/**
 * @author GuoChunbo
 * @create 2021-03-29 9:03
 * @Description: 类的描述
 */
@CrossOrigin
@RestController
public class UploadController {

    @Value("${file.path}")
    String filePath;

    @RequestMapping("/upload")
    public Result upload(MultipartFile file) {
        //保存图片
        try {
            String fileName = UUID.randomUUID() + ".png";
            if (!file.isEmpty()) {
                file.transferTo(new File(filePath + fileName));
                return Result.ok(fileName);
            }
        } catch (IOException e) {
            e.printStackTrace();
        }
        return Result.error("图片上传失败");
    }

    @RequestMapping("/showImg")
    public void showImg(String imgName, HttpServletResponse response) {
        try {
            FileInputStream fis = new FileInputStream(filePath + imgName);
            byte[] bytes = new byte[fis.available()];
            fis.read(bytes);
            fis.close();

            response.getOutputStream().write(bytes);
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
}
